package com.flute.icrawler.app.monitor;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 被监控的对象 传入的对象中属性如果有GET和SET方法都将被注册到MAP中 CrawlMonitor
 * 会将此对象中的MAP映射关系取出来，建立对该属性值的监控 是一个装饰器decorator 用来包装普通的对象
 * 
 */
public class CrawlMonitoredEntity {

	private Object Object = null;

	private CrawlMonitorConfig crawlConfig = null;

	public CrawlMonitoredEntity(Object monitoredObject) {
		this.Object = monitoredObject;

		// 默认建立属性和其对应GET SET方法的映射
		crawlConfig = new CrawlMonitorConfig();
		buildGetMethod();
		buildSetMethod();
	}

	public CrawlMonitoredEntity(Object monitoredObject,
			CrawlMonitorConfig crawlConfig) {
		this.Object = monitoredObject;
		this.crawlConfig = crawlConfig;
	}

	public boolean containReadAttribute(String strField) {

		return crawlConfig.containReadField(strField);
	}

	public boolean containWriteAttribute(String strField) {

		return crawlConfig.containWriteField(strField);
	}

	private void buildGetMethod() {

		Field[] fields = Object.getClass().getDeclaredFields();

		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			Method method = null;
			try {
				method = Object.getClass().getMethod(
						"get" + fieldName.substring(0, 1).toUpperCase()
								+ fieldName.substring(1));
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				continue;
			}
			if (null != method) {
				crawlConfig.putReadMethod(fieldName, method);
			}

		}

	}

	private void buildSetMethod() {

		Field[] fields = Object.getClass().getDeclaredFields();

		for (int i = 0; i < fields.length; i++) {
			String fieldName = fields[i].getName();

			Method method = null;
			try {
				method = Object.getClass().getMethod(
						"set" + fieldName.substring(0, 1).toUpperCase()
								+ fieldName.substring(1), fields[i].getType());
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				continue;
			}
			if (null != method) {
				crawlConfig.putWriteMethod(fieldName, method);
			}

		}

	}

	public Object getMonitoredObject() {
		return Object;
	}

	public Method getGetMethod(String strField) {
		return crawlConfig.getReadMethod(strField);
	}

	public Method getSetMethod(String strField) {
		return crawlConfig.getWriteMethod(strField);
	}

	public String[] getMonitoredFieldNames() {
		return crawlConfig.getMonitoredFieldNames();
	}

}
